<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @change="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="tableList" @expand-change="expandHandle">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="res">
                  {{ formatStatus (res.row.status) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text">退租</el-button>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editHandle(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delExterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <!--
        1. 根据后端的数据 渲染分页组件
           分页核心逻辑：页数 = 总数 / 每页条数(默认10条)
        2. 点击分页中的每一页切换table中的显示
           拿到当前点击的是第几页
           使用当前页的去后端获取数据
       -->
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChange"
      />
    </div>
    <!-- 弹框 -->
    <!--
      点击蒙层区域和小叉号会自动执行close事件
     -->
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
      @open="openDialog"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :http-request="upload"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="file"
              action="#"
              :http-request="upload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmCreateRent">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getExterpriseListAPI, getRentListAPI, getRentBuildListAPI, uploadAPI, createRentAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      params: {
        page: 1, // 当前页数
        pageSize: 2, // 每页条数
        name: '' // 搜索的关键词 企业名称
      },
      tableList: [], // 列表
      total: 0,
      dialogVisible: false,
      buildingList: [],
      rentForm: {
        // 合同表单
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        // 合同校验规则对象
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }

    }
  },
  created() {
    this.getList()
  },
  methods: {
    async upload(res) {
      console.log(res)
      // 1. 得到了File对象
      const file = res.file
      // 2. 创建一个formData实例
      const formData = new FormData()
      // 3. 往实例中按照接口文档格式添加字段和值
      formData.append('file', file)
      formData.append('type', 'contract')
      // 4. 调用接口
      const _res = await uploadAPI(formData)
      this.rentForm.contractId = _res.data.id
      this.rentForm.contractUrl = _res.data.url
    },
    // 新增合同
    addRent(id) {
      // 1. 打开弹框
      this.dialogVisible = true
      // 2. 记录当前项的id参数
      this.rentForm.enterpriseId = id
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
      // this.rentForm.buildingId = null // 楼宇id
      // this.rentForm.contractId = null // 合同id
      // this.rentForm.contractUrl = // 合同Ur]
      // this.rentForm.enterpriseId = null // 企业名称
      // this.rentForm.type = // 合同类型
      // this.rentForm.rentTime = [] // 合同时间
      this.$refs.addForm.resetFields()
      this.$refs.file.clearFiles()

      // 清空表单 (reset方法在dialog一起使用的时候会有bug 手动控制数据初始化 + reset方法调用)
    },
    async getList() {
      const res = await getExterpriseListAPI(this.params)
      this.tableList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: []
        }
      })
      // this.tableList = res.data.rows
      this.total = res.data.total
    },
    // 准备查询后调方法
    doSearch() {
      this.params.page = 1
      this.getList()
    },
    pageChange(page) {
      console.log(page)
      this.params.page = page
      this.getList()
    },
    editHandle(id) {
      this.$router.push({
        path: '/enterpriseAdd',
        query: {
          id
        }
      })
    },
    delExterprise() {
    },
    // 3. 只有展开时获取数据并绑定
    async expandHandle(row, rows) {
      console.log('展开或关闭', row, rows)
      // 请求优化：只有在展开时才发送网络请求
      // 判断当前row是否能在rows中找到  查找方法 - find
      const isExpend = rows.find(item => item.id === row.id)
      if (isExpend) {
        const res = await getRentListAPI(row.id)
        // eslint-disable-next-line require-atomic-updates
        row.rentList = res.data
      }
    },
    formatStatus(statu) {
      // console.log(statu)
      const MAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退组'
      }
      return MAP[statu]
    },
    async getBuildinglist() {
      const res = await getRentBuildListAPI()
      this.buildingList = res.data
    },
    openDialog() {
      this.getBuildinglist()
    },
    async confirmCreateRent() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          await createRentAPI({
            buildingId: this.rentForm.buildingId, // 楼宇id
            contractId: this.rentForm.contractId, // 合同id
            contractUrl: this.rentForm.contractUrl, // 合同Url
            enterpriseId: this.rentForm.enterpriseId, // 企业名称
            type: this.rentForm.type, // 合同类型
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1]
          })
          // 关闭弹框
          this.dialogVisible = false
          // 提示用户
          this.$message({
            type: 'success',
            message: '创建合同成功'
          })
          // 刷新列表
          this.getList()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
